package com.ytjj.qmyx.mall.controller.app;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.ytjj.common.api.CommonResult;
import com.ytjj.common.controller.BaseController;
import com.ytjj.common.model.MyWalletResponse;
import com.ytjj.common.model.UsersResponse;
import com.ytjj.common.service.RedisService;
import com.ytjj.common.utils.TokenUtil;
import com.ytjj.qmyx.mall.constants.RedisConstants;
import com.ytjj.qmyx.mall.enums.ActivityTypeEnums;
import com.ytjj.qmyx.mall.model.Product;
import com.ytjj.qmyx.mall.model.UsersGetuiInfo;
import com.ytjj.qmyx.mall.model.dto.AppNewLifeHallIndexGroupProductDto;
import com.ytjj.qmyx.mall.model.dto.NewAppActivityDto;
import com.ytjj.qmyx.mall.model.dto.NewAppIndexActivityDto;
import com.ytjj.qmyx.mall.model.request.AppGetuiSaveRequest;
import com.ytjj.qmyx.mall.model.response.AppIndexTopResponse;
import com.ytjj.qmyx.mall.service.ActivityService;
import com.ytjj.qmyx.mall.service.GroupActivityService;
import com.ytjj.qmyx.mall.service.UsersGetuiInfoService;
import com.ytjj.qmyx.users.client.UsersClient;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.cloud.context.config.annotation.RefreshScope;
import org.springframework.util.CollectionUtils;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.annotation.Resource;
import java.math.BigDecimal;
import java.util.*;

/**
 * app首页接口
 */
@RestController
@RequestMapping("/newIndex")
@Slf4j
@RefreshScope
public class NewAppIndexController extends BaseController {
    @Resource
    private ActivityService activityService;
    @Autowired
    private RedisService redisService;
    @Autowired
    private GroupActivityService groupActivityService;
    @Resource
    private UsersGetuiInfoService usersGetuiInfoService;
    @Autowired
    private UsersClient usersClient;
    @Value("${app.activity.jump.url:http://192.168.10.7:8084/#/pages/}")
    private String jumpUrl;

    /**
     * 获取首页专题商品
     * (专题活动入口展示的商品)
     */
    @GetMapping("/getHomeSubjectProduct")
    public CommonResult getHomeSubjectProduct() {
        return activityService.getHomeSubjectProduct();
    }

    /**
     * 获取零元测评商品
     * 只取2条
     * @return
     */
    @GetMapping("/zeroEvaluation")
    public CommonResult zeroEvaluationProductLimit() {
        String token = TokenUtil.getToken();
        Integer id = null;
        if ( null != token && "" != token) {
            UsersResponse currentUser = getCurrentUser();
            id = currentUser.getId();
        }

        AppIndexTopResponse activityProducts = activityService.queryRandomProductByActivityTypeAndLimit(ActivityTypeEnums.ZERO_EVALUATION.name(), 2, id);
        return CommonResult.success(activityProducts);
    }

    /**
     * APP全局活动开关
     * @return
     */
    @GetMapping("/globalConfig")
    public CommonResult globalConfig() {
        String group_switch = redisService.get(RedisConstants.SWITCH_APP_ACTIVITY + ActivityTypeEnums.GROUP_WORK.name());//拼团开关
        Map<String, String> result = new HashMap<>();
        result.put(ActivityTypeEnums.GROUP_WORK.name(), group_switch);
        return CommonResult.success(result);
    }

    @GetMapping("/list")
    public CommonResult list() {
        String sortStrs = redisService.getMapString("sys:config", "SORT");
        String[] sortStr = sortStrs.split(",");
        int[] sortStri = Arrays.stream(sortStr).mapToInt(Integer::parseInt).toArray();
        NewAppActivityDto returnDto = new NewAppActivityDto();
        returnDto.setSortStr(sortStri);

        String sysConfig = "sys:config";
        try {
            returnDto.setTopPic(redisService.getMapString(sysConfig, "APP_ACTIVITY_TOP_PIC"));//商城顶部图片
        } catch (Exception e) {
            returnDto.setTopPic("");
        }
        try {
            returnDto.setTopUrl(redisService.getMapString(sysConfig, "APP_ACTIVITY_TOP_PIC_URL")); //商城顶部图片跳转url
        } catch (Exception e) {
            returnDto.setTopUrl("");
        }
        String imgRedis = redisService.getMapString(sysConfig, "APP_ACTIVITY_PICS");//商城所有图片
        String subTitleRedis = redisService.getMapString(sysConfig, "APP_ACTIVITY_SUBTITLE");//商城所有副标题
        String bgColorRedis = redisService.getMapString(sysConfig, "APP_ACTIVITY_BGCOLOR");//
        String titleRedis = redisService.getMapString(sysConfig, "APP_ACTIVITY_TITLE");
        String priceRedis = redisService.getMapString(sysConfig, "APP_ACTIVITY_PRICE");
        String labelPicRedis = redisService.getMapString(sysConfig, "APP_ACTIVITY_LABELPICS");
        String[] imgs = imgRedis.split(",");
        String[] subTitles = subTitleRedis.split(",");
        String[] colors = bgColorRedis.split(",");
        String[] titles = titleRedis.split(",");
        String[] prices = priceRedis.split(",");
        String[] labelPics = labelPicRedis.split(",");



        List<NewAppIndexActivityDto> result = new LinkedList<>();

        NewAppIndexActivityDto dto1 = doNewHandleActivityData(0, titles, subTitles, imgs, colors, prices, labelPics);
        NewAppIndexActivityDto dto2 = doNewHandleActivityData(1, titles, subTitles, imgs, colors, prices, labelPics);
        NewAppIndexActivityDto dto3 = doNewHandleActivityData(2, titles, subTitles, imgs, colors, prices, labelPics);
        NewAppIndexActivityDto dto4 = doNewHandleActivityData(3, titles, subTitles, imgs, colors, prices, labelPics);
        NewAppIndexActivityDto dto5 = doNewHandleActivityData(4, titles, subTitles, imgs, colors, prices, labelPics);
        NewAppIndexActivityDto dto6 = doNewHandleActivityData(5, titles, subTitles, imgs, colors, prices, labelPics);
        NewAppIndexActivityDto dto7 = doNewHandleActivityData(6, titles, subTitles, imgs, colors, prices, labelPics);

        UsersResponse usersResponse = null;
        try {
            usersResponse = this.getCurrentUser();
        } catch (Exception e) {
            log.info("===未登录===");
            returnDto.setGroupAmount(BigDecimal.ZERO);
            returnDto.setScore(0);
        }
        if (null != usersResponse) {
            MyWalletResponse walletResponse = usersClient.getMyWalletRpc(usersResponse.getId());
            returnDto.setGroupAmount(walletResponse.getGroupAmount());

            returnDto.setScore(walletResponse.getScore());
        }

        result.add(dto1);result.add(dto2);result.add(dto3);result.add(dto4);result.add(dto5);result.add(dto6);result.add(dto7);

        returnDto.setList(result);
        return CommonResult.success(returnDto);
    }

    private NewAppIndexActivityDto doNewHandleActivityData(int index, String[] titles, String[] subTitles, String[] imgs, String[] colors, String[] prices, String[] labelPics) {
        NewAppIndexActivityDto dto = new NewAppIndexActivityDto();
        dto.setTitle(titles[index]);
        List<AppNewLifeHallIndexGroupProductDto> imgDtos = new ArrayList<>();
        AppNewLifeHallIndexGroupProductDto imgDto1 = new AppNewLifeHallIndexGroupProductDto();
        dto.setSubTitle(subTitles[index]);
        if (index == 4) {
            dto.setBgColor(colors[0]);
        }
        if (0 == index) {
            imgDto1.setProductImg(imgs[0]);
        }else {
            imgDto1.setProductImg(imgs[2 * index]);
        }
        if (index == 4) {
            imgDto1.setPrice(prices[0]);
            AppNewLifeHallIndexGroupProductDto imgDto2 = new AppNewLifeHallIndexGroupProductDto();
            imgDto2.setProductImg(imgs[2 * index + 1]);
            imgDto2.setPrice(prices[1]);
            imgDtos.add(imgDto2);
            AppNewLifeHallIndexGroupProductDto imgDto3 = new AppNewLifeHallIndexGroupProductDto();
            imgDto3.setProductImg(imgs[2 * index + 2]);
            imgDto3.setPrice(prices[2]);
            imgDtos.add(imgDto3);
            AppNewLifeHallIndexGroupProductDto imgDto4 = new AppNewLifeHallIndexGroupProductDto();
            imgDto4.setProductImg(imgs[2 * index + 3]);
            imgDto4.setPrice(prices[3]);
            imgDtos.add(imgDto4);
        } else if(index == 5 ) {
            imgDto1.setProductImg(imgs[2 * index + 2]);
            imgDto1.setPrice(prices[4]);
            AppNewLifeHallIndexGroupProductDto imgDto2 = new AppNewLifeHallIndexGroupProductDto();
            imgDto2.setProductImg(imgs[2 * index + 3]);
            imgDto2.setPrice(prices[5]);
            imgDtos.add(imgDto2);
        }else if (index == 6) {
            imgDto1.setProductImg(imgs[2 * index + 2]);
            imgDto1.setPrice(prices[6]);
            AppNewLifeHallIndexGroupProductDto imgDto2 = new AppNewLifeHallIndexGroupProductDto();
            imgDto2.setProductImg(imgs[2 * index + 3]);
            imgDto2.setPrice(prices[7]);
            imgDtos.add(imgDto2);
        } else {
            AppNewLifeHallIndexGroupProductDto imgDto2 = new AppNewLifeHallIndexGroupProductDto();
            imgDto2.setProductImg(imgs[2 * index + 1]);
            imgDtos.add(imgDto2);
        }

        imgDtos.add(imgDto1);
        dto.setProducts(imgDtos);
        if (0 == index) {
            dto.setMainUrl(labelPics[0]);
            dto.setActivityType("groupBuy");//全民拼团
            dto.setJumpUrl(jumpUrl + "group/list");
        }else if (1 == index) {
            dto.setActivityType("caseScore");//积分兑换
            dto.setJumpUrl(jumpUrl + "integralCenter/index");
        }else if (2 == index) {
            dto.setActivityType("caseCoupon");//生活馆
            dto.setJumpUrl(jumpUrl + "lifeHallWithin/discover");
        }else if (3 == index) {
            dto.setActivityType("rechargeCoupon");//大额神券
            dto.setJumpUrl(jumpUrl + "coupon/index");
        }else if (4 == index) {
            dto.setMainUrl(labelPics[1]);
            dto.setActivityType("oldForNew");//全民补贴
            dto.setJumpUrl(jumpUrl + "fullSubsidy/index");
        }else if (5 == index) {
            dto.setActivityType("brand");//品牌馆
            dto.setJumpUrl(jumpUrl + "brandClassify/brandClassify");//
        }else if (6 == index) {
            dto.setActivityType("LIVE");//充值中心
            dto.setJumpUrl("/qmyx/topup/activity");
        }
        return dto;
    }

    private NewAppIndexActivityDto doHandleActivityReturnData(String type, List<AppNewLifeHallIndexGroupProductDto> datas) {
        String sysConfig = "sys:config";
        NewAppIndexActivityDto dto = new NewAppIndexActivityDto();

        String title = "";
        try {
            title = redisService.getMapString(sysConfig, type + "_TITLE");
        } catch (Exception e) {
            title = "";
        }
        String subTitle = "";
        try {
            subTitle = redisService.getMapString(sysConfig, type + "_SUBTITLE");
        } catch (Exception e) {
            subTitle = "";
        }
        String mainUrl = "";
        try {
            mainUrl = redisService.getMapString(sysConfig, type + "_MAINURL");
        } catch (Exception e) {
            mainUrl = "";
        }
        String activityPrice = "";
        try {
            activityPrice = redisService.getMapString(sysConfig, type + "_LABALPRICE");
        } catch (Exception e) {
            activityPrice = "";
        }

        String btnPic = "";
        String bgColor = "";
        try {
            btnPic = redisService.getMapString(sysConfig, type + "_BTNPIC");
        } catch (Exception e) {
            btnPic = "";
        }

        try {
            bgColor = redisService.getMapString(sysConfig, type + "_BGCOLOR");
        } catch (Exception e) {
            bgColor = "";
        }


        dto.setTitle(title);
        dto.setSubTitle(subTitle);
        dto.setMainUrl(mainUrl);
        dto.setProducts(datas);
        dto.setActivityType(type);
        dto.setJumpUrl(jumpUrl + "choiceOfficer/choiceOfficer");
        dto.setBtnPic(btnPic);
        dto.setBgColor(bgColor);
        switch (type) {
            case "CASESCORE":
                dto.setActivityType("caseScore");
                dto.setJumpUrl(jumpUrl + "integralCenter/index");
                break;
            case "RECHARGECOUPON":
                dto.setActivityType("rechargeCoupon");
                dto.setJumpUrl("/topup/activity");
                break;
            case "SECKILL":
                dto.setActivityType("seckill");
                dto.setJumpUrl(jumpUrl + "topup/activity");
                break;
            case "CASHCOUPON":
                dto.setActivityType("caseCoupon");
                dto.setJumpUrl(jumpUrl + "coupon/index");
                break;
            case "GROUPBUY":
                dto.setActivityType("groupBuy");
                dto.setJumpUrl(jumpUrl + "group/list");
                break;
            case "OLDFORNEW":
                dto.setActivityType("oldForNew");
                dto.setJumpUrl(jumpUrl + "fullSubsidy/index");
                break;
        }
        dto.setActivityPrice(BigDecimal.valueOf(Long.parseLong(activityPrice)));
        return dto;
    }

    /**
     * 获取拼团数据
     * @return
     */
    public List<AppNewLifeHallIndexGroupProductDto> doGroupDatas() {
        String curPositionHaveRecord = redisService.get(RedisConstants.CUR_GROUP_DATAS_HAVEVALUE);//获取当前分段中是否还有数据 1-有数据,表示不需要重新从数据库中获取
        if (!StringUtils.isEmpty(curPositionHaveRecord) && curPositionHaveRecord.equals("1")) {
            Set<Object> curPositionDataList = redisService.sGet(RedisConstants.CUR_GROUP_DATAS);
            List<AppNewLifeHallIndexGroupProductDto> results = new LinkedList<>();//当前分段中补贴商品数据
            if (!CollectionUtils.isEmpty(curPositionDataList)) {
                curPositionDataList.stream().forEach(s -> {
                    JSONObject objJsonStr = JSON.parseObject(s.toString());
                    AppNewLifeHallIndexGroupProductDto dto = JSONObject.toJavaObject(objJsonStr, AppNewLifeHallIndexGroupProductDto.class);
                    results.add(dto);
                });
            }
            return results;
        }
        String curPositionStr = redisService.get(RedisConstants.CUR_POSITION_INDEX_GROUP);
        Integer curPosition = 0;
        if (StringUtils.isEmpty(curPositionStr)) {
            curPosition = 0;
            redisService.set(RedisConstants.CUR_POSITION_INDEX_GROUP, String.valueOf(curPosition));
        }else {
            curPosition = Integer.parseInt(curPositionStr) + 1;
            String pageTotalStr = redisService.get(RedisConstants.GROUP_PAGES);
            Integer pageTotal = Integer.parseInt(pageTotalStr);
            if (curPosition > pageTotal) {
                curPosition = 0;
            }
            redisService.set(RedisConstants.CUR_POSITION_INDEX_GROUP, String.valueOf(curPosition));
        }
        Integer pageNum = curPosition;
        Integer pageSize = 2;
        List<AppNewLifeHallIndexGroupProductDto> groupProductDatas = groupActivityService.queryFineGroupListByNewLifeHall(pageNum, pageSize);
        return groupProductDatas;
    }

    /**
     * 获取补贴数据
     * @return
     */
    public List<AppNewLifeHallIndexGroupProductDto> doOldForNewDatas() {
        String curPositionHaveRecord = redisService.get(RedisConstants.CUR_POSITION_DATAS_HAVEVALUE);//获取当前分段中是否还有数据 1-有数据,表示不需要重新从数据库中获取
        if (!StringUtils.isEmpty(curPositionHaveRecord) && curPositionHaveRecord.equals("1")) {
            Set<Object> curPositionDataList = redisService.sGet(RedisConstants.CUR_POSITION_DATAS);
            List<AppNewLifeHallIndexGroupProductDto> results = new LinkedList<>();//当前分段中补贴商品数据
            if (!CollectionUtils.isEmpty(curPositionDataList)) {
                curPositionDataList.stream().forEach(s -> {
                    JSONObject objJsonStr = JSON.parseObject(s.toString());
                    AppNewLifeHallIndexGroupProductDto dto = JSONObject.toJavaObject(objJsonStr, AppNewLifeHallIndexGroupProductDto.class);
                    results.add(dto);
                });
            }
            return results;
        }
        String curPositionStr = redisService.get(RedisConstants.CUR_POSITION_INDEX_OLDFORNEW);
        Integer curPosition = 0;
        if (StringUtils.isEmpty(curPositionStr)) {
            curPosition = 0;
            redisService.set(RedisConstants.CUR_POSITION_INDEX_OLDFORNEW, String.valueOf(curPosition));
        }else {
            curPosition = Integer.parseInt(curPositionStr) + 1;
            String pageTotalStr = redisService.get(RedisConstants.OLD_FOR_NEW_PAGES);
            Integer pageTotal = Integer.parseInt(pageTotalStr);
            if (curPosition > pageTotal) {
                curPosition = 0;
            }
            redisService.set(RedisConstants.CUR_POSITION_INDEX_OLDFORNEW, String.valueOf(curPosition));
        }
        Integer pageNum = curPosition;
        Integer pageSize = 4;
        List<AppNewLifeHallIndexGroupProductDto> list = activityService.getAllListByNew(pageNum, pageSize, null);
        return list;
    }

    /**
     * 指定活动类型查询信息
     * @param activityType 活动类型
     * @return
     */
    public List<AppNewLifeHallIndexGroupProductDto> doFourDatasByActivityByPoint(String activityType) {
        List<AppNewLifeHallIndexGroupProductDto> result = new LinkedList<>();
        List<Product> activityProducts = activityService.getProductByActivityType(activityType, activityType.equals("CASH_COUPON") ? 4 : 2);
        if (!CollectionUtils.isEmpty(activityProducts)) {
            activityProducts.stream().forEach(s -> {
                AppNewLifeHallIndexGroupProductDto dto = new AppNewLifeHallIndexGroupProductDto();
                dto.setId(s.getId());
                dto.setProductImg(s.getProductImg());
                if ("CASH_SCORE".equals(activityType) || "RECHARGE_COUPON".equals(activityType)
                        || "SECKILL".equals(activityType) || "CASH_COUPON".equals(activityType)) {
//                    dto.setPrice(s.getActivityMax());
                } else {
//                    dto.setPrice(s.getPrice());
                }
                result.add(dto);
            });
        }
        return result;
    }

    /**
     * 保存极光信息
     * @return
     */
    @PostMapping("/saveAppGetuiInfo")
    public CommonResult saveAppGetuiInfo(@RequestBody AppGetuiSaveRequest request) {
        if (StringUtils.isEmpty(request.getPushId())) {
            return CommonResult.success();
        }
        log.info("===push jiguan id======{}", request.getPushId());
        String imei = TokenUtil.getImei();
        String oaid = TokenUtil.getOaid();
        String osVersion = String.valueOf(TokenUtil.getOsVersion());
        String channel = TokenUtil.getChannel();
        String source = TokenUtil.getSource();//ios/android
        UsersResponse usersResponse = null;
        try {
            usersResponse = getCurrentUser();
        } catch (Exception e) {
            return CommonResult.success();
        }
        if (null == usersResponse) {
            return CommonResult.success();
        }
        log.info("===push jiguan usersResponse.id======{}", usersResponse.getId());
        UsersGetuiInfo usersGetuiInfo = usersGetuiInfoService.getByUserId(usersResponse.getId());
        if (null == usersGetuiInfo) {
            usersGetuiInfo = new UsersGetuiInfo();
        }
        usersGetuiInfo.setGetuiId(request.getPushId());
        usersGetuiInfo.setImei(imei);
        usersGetuiInfo.setOaid(oaid);
        usersGetuiInfo.setOsVersion(osVersion);
        usersGetuiInfo.setPlatform(source);
        usersGetuiInfo.setUserId(null == usersResponse.getId() ? null : usersResponse.getId());
        usersGetuiInfo.setOffFlag(request.getOffFlag());
        usersGetuiInfo.setTel(usersResponse.getTel());
        if (null == usersGetuiInfo.getId()) {
            usersGetuiInfo.setCreateTime(new Date());
            int result = usersGetuiInfoService.insert(usersGetuiInfo);
        } else {
            usersGetuiInfo.setUpdateTime(new Date());
            int result = usersGetuiInfoService.update(usersGetuiInfo);
        }
        return CommonResult.success();
    }
}
